package com.study.student_chuji.demos.controller;

import com.study.student_chuji.demos.pojo.Product;
import com.study.student_chuji.demos.service.ProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.List;


@Controller
public class AdminProductController {
    @Autowired
    private ProductService productService;



    @GetMapping("/getProductTable")
    public String getProductTable(Model model) {
        model.addAttribute("productList" ,productService.getProductList());
        return "admin/productTable";
    }
    @DeleteMapping("/deleteProduct")
    @ResponseBody
    public String deleteProduct(Long id,Model model) {
        productService.deleteProductById(id);

//        model.addAttribute("productList" ,productService.getProductList());
        return "OK";
    }
    @GetMapping("/toProductForm")
    public String toProductForm(@RequestParam(required = false) Long id, Model model) {
        if (id != null) { // 有ID：修改，回显商品数据
            Product product = productService.getProductById(id);
            model.addAttribute("product", product);
        }
        return "admin/productForm"; // 复用同一个表单页面
    }

    // 实验五新增2：新增商品（接收前端POST请求，返回成功标识）
    @PostMapping("/addProduct")
    @ResponseBody // 重要：返回JSON/字符串，而非页面
    public String addProduct(@RequestBody Product product) {
        productService.addProduct(product);
        return "OK"; // 给前端判断是否成功
    }

    // 实验五新增3：修改商品（接收前端PUT请求，判断ID有效性）
    @PutMapping("/updateProduct")
    @ResponseBody
    public String updateProduct(@RequestBody Product product) {
        // 后端校验：ID不存在则返回错误
        if (product.getId() == null || productService.getProductById(product.getId()) == null) {
            return "ERROR";
        }
        productService.updateProduct(product);
        return "OK";
    }
    @GetMapping("/searchProduct")
    public String searchProduct(Model model,String name,@RequestParam(value = "minAmount",required = false) Integer min,Integer maxAmount,String type){
        List<Product> List = productService.searchProduct(name,min,maxAmount,type);
        model.addAttribute("productList",List);
        return "admin/productTable";
    }

}
